﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TruckWatch.Cloud.Models;
using System.Data;

namespace TruckWatch.Cloud.DAL
{
    public static class TripStatusDAL
    {
        public static List<TripStatusNEF> GetAllTripStatusesByDriver(int driverId)
        {
            ParamBuilder pb = new ParamBuilder();
            pb.AddParam(SqlDbType.Int, "@DriverId", driverId);

            string sql = @"
select 
	Id, TripId, StatusDate,StatusMessage, StatusReason,DriverId 
from 
	Tripstatus
where
	DriverId = @DriverId";

            List<TripStatusNEF> tripStatuses = new List<TripStatusNEF>();
            DataTable dt = DataGeneral.GetDataTable(sql, pb.Parameters);

            foreach (DataRow row in dt.Rows)
            {
                TripStatusNEF item = new TripStatusNEF();
                item.Id = (int)row["id"];
                item.TripId = row["TripId"] == DBNull.Value ? 0 : (int)row["TripId"];
                item.StatusDate = ((DateTime)row["StatusDate"]).AddHours(-5); // converting UTC to CDT
                item.StatusMessage = row["StatusMessage"] as string;
                item.StatusReason = row["StatusReason"] as string;
                item.DriverId = (int)row["DriverId"];

                tripStatuses.Add(item);
            }

            return tripStatuses;
        }

        public static void UpdateTripStatus(TripStatusNEF tripStatus)
        {
            ParamBuilder pb = new ParamBuilder();
            pb.AddParam(SqlDbType.Int, "@TripId", tripStatus.TripId == 0 ? (object)DBNull.Value : (object)tripStatus.TripId);
            pb.AddParam(SqlDbType.DateTime, "@StatusDate", tripStatus.StatusDate.ToUniversalTime());
            pb.AddParam(SqlDbType.VarChar, "@StatusMessage", tripStatus.StatusMessage);
            pb.AddParam(SqlDbType.VarChar, "@StatusReason", tripStatus.StatusReason);
            pb.AddParam(SqlDbType.Int, "@DriverId", tripStatus.DriverId);

            string sql = @"
INSERT INTO TripStatus
           (TripId,StatusDate,StatusMessage,StatusReason,DriverId)
     VALUES
           (@TripID,@StatusDate,@StatusMessage,@StatusReason,@DriverId)";

            DataGeneral.ExecuteNonQuery(sql, pb.Parameters, false);
        }

    }
}
